import httpapi from './api'
import store from '../vuex'
import { Message } from 'element-ui';
export default function install(Vue,router){
//	Vue.http.headers.common['DOMAIN'] = 'http://172.16.18.224:8090';
	Vue.http.interceptors.push((request, next) => {
    store.commit('REQUEST_ING');
	    next((response) => {
        store.commit('REQUEST_END');
	    	if(response.status===504||response.status===404||response.status===500){
					Message({
						showClose: true,
						message: '网络拥堵，请求超时，请稍后再试！',
						type: 'error'
					});
	    	}
	    	else if(response.status===403){
					Message({
	          showClose: true,
	          message: response.body.ErrorMsg,
	          type: 'error'
	        });
        }
    		else if(response.status===401){
          Message({
	          showClose: true,
	          message: '登录信息已失效，请重新登录！',
	          type: 'error'
	        });
          sessionStorage.clear();
          setTimeout(()=>{
            router.push({'name':'login'});
          },2000)
	    	}
	    	else if(!response.ok){
					Message({
	          showClose: true,
	          message: '当前网络质量不佳，请刷新页面重试！',
	          type: 'error'
	        });
	    	}
	    	else if(!response.body.Success){
					Message({
	          showClose: true,
	          message: response.body.ErrorMsg,
	          type: 'error'
	        });
        }
	    	// else if(response.body.code!=='000000'){
        //   Message.error(response.body.msg);
	    	// }
	    	return response
	    })
	});
    function rosourceXHRPromise(method, args, type,params){
      var xhrPromise =!!params?method[type].call(null,params,args):method[type].call(null,args),
      promise = {
          then(resolvecb,rejectcb){
             xhrPromise.then((res)=>{
                var body = res.body
                try{
                    typeof body == 'string' && (body = JSON.parse(body))
                }catch(err){}
                if(body.Success){
                    resolvecb && resolvecb(body)
                }else {
                    rejectcb && rejectcb(body)
                    // $msg.show(body.message)
                }
            },(res)=>{
                rejectcb && rejectcb(res.body)
            })
          }
      }
      return  Promise.resolve(promise)
    }
    // 重写 Vue.resource(url)[method]
    var resource = Vue.resource
    var apiObj=httpapi.httpapi.reduce((curr,api)=>{
        var method = resource(api.api,{},{},{vuem:api.name})
         curr[api.name] = (data={},params)=> {
            let type=api.type==='post'?'save':api.type
            return rosourceXHRPromise(method,data,type,params)
        }
        return curr
    },{})
    Vue.prototype.$ajax=apiObj;
    Vue.prototype.$api=httpapi.apiText;
}
